var express = require('express');
var db = require('./db.js')

var router = express.Router()
var bodyParser = require('body-parser');
var md5 = require('md5-nodejs');
var urlencodedParser = bodyParser.urlencoded({
    extended: false
})

var multer = require('multer');

//头像上传
// var upload = multer({
//     dest: 'upload/'
// })


var storage = multer.diskStorage({
    //发布到什么地方
    destination: function (req, file, cb) {
        cb(null, 'upload/')
    },
    //重新命名文件名
    filename: function (req, file, cb) {
        //截取后缀名
        let extName = file.originalname.slice(file.originalname.lastIndexOf('.'))
        cb(null, file.fieldname + '-' + Date.now() + extName)
    }
})

var upload = multer({
    storage: storage
})

router.post('/upload', upload.single('avatar'), function (req, res, next) { //single选择一张('字段名')
    var file = req.file;
    res.send(db.hand({
        avatar: file.filename
    }))
})

//验证用户名
router.get('/verifyLoginName', async function (req, res) {
    var {
        loginName
    } = req.query;
    let sql = `select * from users where loginName='${loginName}'`
    const data = await db.doSql(sql)
    if (data[0]) {
        res.send(db.errFn(data))
    } else {
        res.send(JSON.stringify(db.hand(data)))
    }
})

//注册
router.post('/register', urlencodedParser, (req, res) => {
    var {
        name,
        age,
        gender,
        edu,
        loginName,
        loginKey,
        introduction,
        avatar,
        email = 2606873068
    } = req.body;
    var sql = `insert into users (name,age,gender,edu,loginName,loginKey,introduction,roles,avatar,email) values (?,?,?,?,?,?,?,?,?,?)`;
    var roles = 'editor';
    db.doSql(sql, [name, age, gender, edu, loginName, loginKey, introduction, roles, avatar, email]).then(data => {
        res.send(JSON.stringify(db.hand(data)))
    })
})


router.post('/login', urlencodedParser, async function (req, res) {
    var {
        loginName,
        loginKey
    } = req.body
    console.log(loginName,
        loginKey)
    let sql = `select * from users where loginName='${loginName}' and loginKey='${loginKey}'`;
    console.log(sql)
    const data = await db.doSql(sql)
    if (data[0]) {
        let r = await getToken(data[0].id)
        data[0].token = r;
        res.send(JSON.stringify(db.hand(data)))
    } else {
        res.send(JSON.stringify(db.errFn()))
    }
})
router.get('/info', async function (req, res) {
    var {
        token
    } = req.query;
    let sql = `select u.id,name,roles,avatar,introduction from tokens as t,users as u where t.uid=u.id and t.token='${token}'`
    const data = await db.doSql(sql)
    res.send(JSON.stringify(db.hand(data)))
})

function getToken(uid) {
    let sql = `select * from tokens where uid=${uid}`;
    return new Promise((resolve, reject) => {
        db.doSql(sql).then(data => {
            var token;
            if (data.length > 0 && data[0].token) {
                token = data[0].token
            } else {
                token = md5('zxwx' + uid + Date.now())
                setToken(token, uid)
            }
            resolve(token)
        })
    })
}

function setToken(token, uid) {
    let sql = `insert into tokens (token,uid) values ('${token}',${uid})`
    db.doSql(sql)
}

module.exports = router